package api

import (
	"chaincode/model"
	"chaincode/pkg/utils"
	"encoding/json"
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"
)

func UpdAccountList(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	fmt.Println(len(args))
	fmt.Println("mod6 = " + fmt.Sprint(len(args)%6))
	fmt.Println("链码初始化")
	length := len(args) / 6
	//初始化默认数据
	// var accountIds = [6]string{
	// 	"5feceb66ffc8",
	// 	"6b86b273ff34",
	// 	"d4735e3a265e",
	// 	"4e07408562be",
	// 	"4b227777d4dd",
	// 	"ef2d127de37b",
	// }
	// var userNames = [6]string{"管理员", "①号[SCNUER]", "②号[SCNUER]", "③号[SCNUER]", "④号[SCNUER]", "⑤号[SCNUER]"}
	// var balances = [6]float64{0, 5000000, 5000000, 5000000, 5000000, 5000000}
	//初始化账号数据
	for i := 0; i < length; i++ {
		account := &model.Account{
			AccountId: args[i*6],
			UserName:  args[i*6+1],
			Balance:   float64(5000000),
		}
		if err := utils.WriteLedger(account, stub, model.AccountKey, []string{args[i*6]}); err != nil {
			// 写入账本
			return shim.Error(fmt.Sprintf("%s", err))
		}
	}
	return shim.Success(nil)
}

// QueryAccountList 查询账户列表
func QueryAccountList(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var accountList []model.Account
	results, err := utils.GetStateByPartialCompositeKeys(stub, model.AccountKey, args)
	if err != nil {
		return shim.Error(fmt.Sprintf("%s", err))
	}
	for _, v := range results {
		if v != nil {
			var account model.Account
			err := json.Unmarshal(v, &account)
			if err != nil {
				return shim.Error(fmt.Sprintf("QueryAccountList-反序列化出错: %s", err))
			}
			accountList = append(accountList, account)
		}
	}
	accountListByte, err := json.Marshal(accountList)
	if err != nil {
		return shim.Error(fmt.Sprintf("QueryAccountList-序列化出错: %s", err))
	}
	return shim.Success(accountListByte)
}
